﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Exceptions;
using Core.Extensions;

namespace Core
{
    public class LineReader
    {
        private char[] ColumnSeparators
        {
            get
            {
                return new[] { '\t' };
            }
        }

        protected int number;
        protected String str;
        public String Str
        {
            get
            {
                return str;
            }
        }

        public LineReader(String str, int number)
        {
            if (String.IsNullOrWhiteSpace(str))
                throw new LineIsEmptyException();
            this.str = str;
            this.number = number;
        }

        public Line Read()
        {
            if (!Columns.HasValues())
                throw new UnknownLineFormatException();
            return Line;
        }

        private String[] columns;
        public String[] Columns
        {
            get
            {
                if (columns == null)
                    columns = str.Split(ColumnSeparators, StringSplitOptions.RemoveEmptyEntries).TrimQuotes();
                return columns;
            }
        }

        private String source;
        public String Source
        {
            get
            {
                if (source == null)
                    source = Columns.First();
                return source;
            }
        }

        private Line line;
        public Line Line
        {
            get
            {
                if (line != null)
                    return line;

                DetermineLineType();
                
                line.Number = number;
                return line;
            }
        }

        private void DetermineLineType()
        {
            switch (Source)
            {
                case "DEBUG":
                    line = new DebugLine(str, Columns);
                    break;
                case "APPLICATION":
                    line = new ApplicationLine(str, Columns);
                    break;
                case "SMTPC":
                    line = new SmtpClientLine(str, Columns);
                    break;
                case "SMTPD":
                    line = new SmtpDaemonLine(str, Columns);
                    break;
                case "TCPIP":
                    line = new TcpIpLine(str, Columns);
                    break;
                default:
                    throw new UnknownLineTypeException();
            }
        }
    }
}
